//
//  CWImageGallery.m
//  CWDevelop
//
//  Created by LittoCats on 7/23/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "CWImageGallery.h"

#import "UIImageView+AFNetworking.h"

#import "AFNetworking.h"

#import <objc/message.h>

@interface CWImageGallery () <UIScrollViewDelegate>

@property (nonatomic, strong) NSMutableArray *images;

@property (nonatomic, strong) UIPageControl *pageControl;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, weak) UIView *startView;

@property (nonatomic, strong) NSArray *ImageViewQueue;
@end

@implementation CWImageGallery

+ (void)popWithImages:(NSArray *)images fromView:(UIView *)view withIndex:(NSInteger)index
{
    CWImageGallery *gallery = [[CWImageGallery alloc] init];
    
    gallery.startView = view;
    [gallery.images addObjectsFromArray:images];
    
    [gallery reset];
    [gallery scrollToIndex:index animated:NO];
    [gallery fadeIn];
}

- (void)scrollToIndex:(NSInteger)index animated:(BOOL)animated
{
    _pageControl.currentPage = index < 0 ? 0 : index >= _images.count ? _images.count - 1 : index;
    //当前显示的图像
    [self prepareImageView:_ImageViewQueue[0] AtIndex:_pageControl.currentPage];
    [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width * _pageControl.currentPage, 0) animated:animated];
    
    [self prepareImageView:_ImageViewQueue[1] AtIndex:_pageControl.currentPage + 1];
    [self prepareImageView:_ImageViewQueue[2] AtIndex:_pageControl.currentPage - 1];
}

#pragma mark- UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat pageOffset = scrollView.contentOffset.x / scrollView.frame.size.width;
    NSInteger currentIndex = (NSInteger)(pageOffset * 2);
    NSInteger nextIndex = -1;
    pageOffset = pageOffset - (NSInteger)pageOffset;
    if (pageOffset - 0.5 > 0 && currentIndex - _pageControl.currentPage * 2 == 1)
        nextIndex = currentIndex - _pageControl.currentPage;
    else if (pageOffset - 0.5 < 0 && currentIndex - _pageControl.currentPage * 2 == -2)
        nextIndex = currentIndex - _pageControl.currentPage + 1;
        
    if (nextIndex < 0) return;
    _pageControl.currentPage = nextIndex;
    
    for (UIImageView *imageview in self.ImageViewQueue) {
        if (nextIndex - imageview.tag == 2)
            [self prepareImageView:imageview AtIndex:nextIndex+1];
        if (imageview.tag - nextIndex == 2)
            [self prepareImageView:imageview AtIndex:nextIndex-1];
    }

}
#pragma mark-
- (void)prepareImageView:(UIImageView *)imageview AtIndex:(NSInteger)index
{
    if (index < 0 || index >= _images.count) return;
    CGRect frame = _scrollView.bounds;
    frame.origin.x = frame.size.width * index;
    [imageview setFrame:frame];
    imageview.tag = index;
    [self prepareImageAtIndex:index];
}

#pragma mark-
- (id)init
{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        self.alpha = 0.0;
        self.images = [NSMutableArray new];
        
        self.scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.delegate = self;
        _scrollView.pagingEnabled = YES;
        _scrollView.scrollEnabled = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        [self addSubview:_scrollView];
        
        self.pageControl = [[UIPageControl alloc] init];
        _pageControl.hidesForSinglePage = YES;
        [self addSubview: _pageControl];
        
        [self setBackgroundColor:[UIColor blackColor]];
        
        self.ImageViewQueue = @[[UIImageView new],[UIImageView new],[UIImageView new]];
        for (UIImageView *imageview in _ImageViewQueue) {
            imageview.contentMode = UIViewContentModeScaleAspectFit;
            [_scrollView addSubview:imageview];
        }
    }
    return self;
}

- (void)reset
{
    [_scrollView setContentSize:CGSizeMake(_scrollView.frame.size.width * _images.count, _scrollView.frame.size.height)];
    
    [self.pageControl setNumberOfPages:_images.count];
    [self.pageControl setCurrentPage:0];
    [_pageControl sizeToFit];
    [_pageControl setCenter:CGPointMake(self.frame.size.width / 2, self.frame.size.height - 44)];
    
    CGRect frame = _scrollView.bounds;
    for (int i = 0; i < 3; i ++) {
        UIImageView *imageview = _ImageViewQueue[i];
        frame.origin.x = frame.size.width * i;
        [imageview setFrame:frame];
        imageview.tag = -1;
    }
}

- (void)prepareImageAtIndex:(NSInteger)index
{
    if ([_images[index] isKindOfClass:[UIImage class]]){
        [self displayImageAtIndex:index];
        return;
    }
    //查找缓存
    NSURL *url = [_images[index] isKindOfClass:[NSString class]] ? [NSURL URLWithString:_images[index]] : [_images[index] isKindOfClass:[NSURL class]] ? _images[index] : nil;
    
    //设置默认图片
    [_images replaceObjectAtIndex:index withObject:[UIImage imageNamed:@"CWImageViewPlaceHolder"]];
    [self displayImageAtIndex:index];
    
    if (!url) return;
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    UIImage *cachedImage = [[UIImageView sharedImageCache] cachedImageForRequest:request];
    if (cachedImage) {
        [_images replaceObjectAtIndex:index withObject:cachedImage];
        [self displayImageAtIndex:index];
        return;
    }
    
    //下载image
    __weak __typeof(self)weakSelf = self;
    __block NSInteger blockIndex = index;
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [self imageResponseSerializer];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, UIImage *responseImage) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.images replaceObjectAtIndex:blockIndex withObject:responseImage];
        [strongSelf displayImageAtIndex:blockIndex];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    [objc_msgSend([UIImageView class], NSSelectorFromString(@"af_sharedImageRequestOperationQueue")) addOperation:operation];
    
    
}
- (void)displayImageAtIndex:(NSInteger)index
{
    for (UIImageView *imageview in _ImageViewQueue)
        if (imageview.tag == index)
            [imageview setImage:_images[index]];
}

#pragma mark-
- (id <AFURLResponseSerialization>)imageResponseSerializer {
    static id <AFURLResponseSerialization> _af_defaultImageResponseSerializer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _af_defaultImageResponseSerializer = [AFImageResponseSerializer serializer];
    });
    return _af_defaultImageResponseSerializer;
}

#pragma mark- animation
- (void)fadeIn
{
    CGRect _startRect = _startView.frame;
    [self setCenter:CGPointMake(_startRect.origin.x + _startRect.size.width / 2.0,
                                _startRect.origin.y + _startRect.size.height / 2.0)];
    self.transform = CGAffineTransformScale(CGAffineTransformIdentity,
                                            _startRect.size.width / self.frame.size.width,
                                            _startRect.size.height / self.frame.size.height);
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [window addSubview:self];
    [UIView animateWithDuration:0.3
                     animations:^{
                         [self setCenter:CGPointMake(window.frame.size.width / 2, window.frame.size.height / 2)];
                         self.transform = CGAffineTransformScale(CGAffineTransformIdentity,1.0f,1.0f);
                         self.alpha = 1.0;
                         [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:YES];
                     } completion:^(BOOL finished) {
                         UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fadeOut)];
                         tap.numberOfTapsRequired = 1;
                         [self addGestureRecognizer:tap];
                     }];
}

- (void)fadeOut
{
    CGRect _startRect = _startView.frame;
    [UIView animateWithDuration:0.3
                     animations:^{
                         [self setCenter:CGPointMake(_startRect.origin.x + _startRect.size.width / 2.0,
                                                     _startRect.origin.y + _startRect.size.height / 2.0)];
                         self.transform = CGAffineTransformScale(CGAffineTransformIdentity,
                                                                 _startRect.size.width / self.frame.size.width,
                                                                 _startRect.size.height / self.frame.size.height);
                         self.alpha = 0.0;
                         [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:YES];
                     } completion:^(BOOL finished) {
                         [self removeFromSuperview];
                         [_scrollView setContentOffset:CGPointZero];
                         [self.images removeAllObjects];
                         self.startView = nil;
                     }];
}
@end
